<template>
  <div class="dashboard-index">
    <!-- 今日数据 -->
    <div class="today-data container">
      <div class="head">
        <div class="left">
          <h4 class="head-title">今日数据</h4>
          <span class="head-time">2025.03.27</span>
        </div>
        <div class="right">
          <span class="more">详细数据</span>
          <i class="icon el-icon-arrow-right"></i>
        </div>
      </div>
      <div class="main">
        <div class="overview-list">
          <div class="overview-item">
            <span class="overview-title">营业额</span>
            <span class="overview-num">¥ {{ todayBusinessData.turnover }}</span>
          </div>
          <div class="overview-item">
            <span class="overview-title">有效订单</span>
            <span class="overview-num">{{ todayBusinessData.validOrderCount }}</span>
          </div>
          <div class="overview-item">
            <span class="overview-title">订单完成率</span>
            <span class="overview-num">{{ todayBusinessData.orderCompletionRate }}%</span>
          </div>
          <div class="overview-item">
            <span class="overview-title">评价客单价</span>
            <span class="overview-num">¥ {{ todayBusinessData.unitPrice }}</span>
          </div>
          <div class="overview-item">
            <span class="overview-title">新增用户</span>
            <span class="overview-num">{{ todayBusinessData.newUsers }}</span>
          </div>
        </div>
      </div>
    </div>
    <!-- 订单管理 -->
    <div class="order container">
      <div class="head">
        <div class="left">
          <h4 class="head-title">订单管理</h4>
          <span class="head-time">2025.03.27</span>
        </div>
        <div class="right">
          <span class="more">订单明细</span>
          <i class="icon el-icon-arrow-right"></i>
        </div>
      </div>
      <div class="main">
        <div class="overview-list">
          <div class="overview-item">
            <div class="titie-box">
              <i class="icon el-icon-document-add"></i>
              <span class="overview-title">待接单</span>
            </div>
            <span class="overview-num">{{ ordersManageData.waitingOrders }}</span>
          </div>
          <div class="overview-item">
            <div class="title-box">
              <i class="icon el-icon-bicycle"></i>
              <span class="overview-title">待派送</span>
            </div>
            <span class="overview-num">{{ ordersManageData.deliveredOrders }}</span>
          </div>
          <div class="overview-item">
            <div class="title-box">
              <i class="icon el-icon-document-checked"></i>
              <span class="overview-title">已完成</span>
            </div>
            <span class="overview-num">{{ ordersManageData.completedOrders }}</span>
          </div>
          <div class="overview-item">
            <div class="title-box">
              <i class="icon el-icon-document-delete "></i>
              <span class="overview-title">已取消</span>
            </div>
            <span class="overview-num">{{ ordersManageData.cancelledOrders }}</span>
          </div>
          <div class="overview-item">
            <div class="title-box">
              <i class="icon el-icon-document"></i>
              <span class="overview-title">全部订单</span>
            </div>
            <span class="overview-num">{{ ordersManageData.allOrders }}</span>
          </div>
        </div>
      </div>
    </div>
    <!-- 菜品与套餐总览 -->
    <div class="dish-setmeal">
      <div class="dish container">
        <div class="head">
          <div class="left">
            <h4 class="head-title">菜品总览</h4>
          </div>
          <div @click="$router.push('/dish')" class="right">
              <span class="more">菜品管理</span>
              <i class="icon el-icon-arrow-right"></i>
          </div>
        </div>
        <div class="main">
          <div class="overview-item">
            <div class="title-box">
              <i class="icon el-icon-price-tag"></i>
              <span>已启售</span>
            </div>
            <span class="overview-num">{{ overviewDish.sold }}</span>
          </div>
          <div class="overview-item">
            <div class="title-box">
              <i class="icon el-icon-discount"></i>
              <span>已停售</span>
            </div>
            <span class="overview-num">{{ overviewDish.discontinued }}</span>
          </div>
          <div @click="$router.push('/dish/add')" class="add">
            <i class="icon el-icon-circle-plus-outline"></i>
            <span class="title">新增菜品</span>
          </div>
        </div>
      </div>
      <div class="setmeal container">
        <div class="head">
          <div class="left">
            <h4 class="head-title">套餐总览</h4>
          </div>
          <div @click="$router.push('/setmeal')" class="right">
              <span class="more">套餐管理</span>
              <i class="icon el-icon-arrow-right"></i>
          </div>
        </div>
        <div class="main">
          <div class="overview-item">
            <div class="title-box">
              <i class="icon el-icon-price-tag"></i>
              <span>已启售</span>
            </div>
            <span class="overview-num">{{ overviewSetmeal.sold }}</span>
          </div>
          <div class="overview-item">
            <div class="title-box">
              <i class="icon el-icon-discount"></i>
              <span>已停售</span>
            </div>
            <span class="overview-num">{{ overviewSetmeal.discontinued }}</span>
          </div>
          <div @click="$router.push('/setmeal/add')" class="add">
            <i class="icon el-icon-circle-plus-outline"></i>
            <span class="title">新增套餐</span>
          </div>
        </div>
      </div>
    </div>
    <!-- 订单信息 -->
    <div class="order-info container">
      <div class="head">
        <div class="left">
          <h4 class="title">订单信息</h4>
        </div>
        <div class="right">
          <OrderStatusNavVue @click="handleStatus" :orderStatusNav="orderStatusNav"></OrderStatusNavVue>
        </div>
      </div>
      <div class="main">
        <el-table :data="orderList">
          <el-table-column min-width="177" label="订单号" prop="number"></el-table-column>
          <el-table-column min-width="173" label="订单菜品" prop="orderDishes"></el-table-column>
          <el-table-column min-width="173" label="地址" prop="address"></el-table-column>
          <el-table-column align="center" min-width="281" label="预计送达时间" sortable prop="estimatedDeliveryTime"></el-table-column>
          <el-table-column min-width="173" label="实收金额" prop="amount"></el-table-column>
          <el-table-column min-width="173" label="备注" prop="remark"></el-table-column>
          <el-table-column align="center" class-name="operate" min-width="303" label="操作">
            <template slot-scope="scope">
              <button class="btn" v-if="scope.row.status === 3" @click="handleDelivery(scope.row.id)">派送</button>
              <button class="btn" v-if="scope.row.status === 2" @click="handleTakeOrder(scope.row.id)">接单</button>
              <button class="btn" @click="handleRejectOrder(scope.row.id)">拒单</button>
              <button class="btn" @click="handleViewDetail(scope.row.id)">查看</button>
            </template>
          </el-table-column>
        </el-table>
        <div class="paginate">
          <el-pagination
            layout="total, sizes, prev, pager, next, jumper"
            :page-sizes="[10, 20, 30, 40]"
            :total="pageTotal"
            :page-size.sync="pageSize"
            :current-page.sync="page"
            @size-change="getOrder()"
            @current-change="getOrder()"
          ></el-pagination>
        </div>
      </div>
    </div>
    <DialogOrderDetail
     @update:dialogVisibleOrder="dialogVisibleOrder = $event"
     :dialogVisibleOrder="dialogVisibleOrder"
     :orderDetails="orderDetails"
     :orderDishDetailList="orderDishDetailList"
     @click="handleBtnClick"></DialogOrderDetail>
    <!-- 拒绝原因弹窗 -->
    <el-dialog
     title="拒绝原因"
     :visible.sync="dialogVisibleReject"
     width="45%">
      <div class="reject-box">
        <div>
          <span>拒绝原因：</span>
          <el-select v-model="rejectReason" placeholder="请选择拒绝原因">
            <el-option
            v-for="item in rejectReasonList" :key="item.value"
            :label="item.label"
            :value="item.value"></el-option>
          </el-select>
        </div>
        <div v-if="rejectReason === 4">
          <span>原因：</span>
          <el-input v-model="rejectReasonText" max="20" type="textarea" placeholder="请填写您拒绝的原因（限20字内）"></el-input>
        </div>
      </div>
      <template slot="footer">
          <el-button @click="dialogVisibleReject = false">取消</el-button>
          <el-button @click="rejectOrder" type="primary">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { getBusinessData, getOrdersData, getOverviewDish, getOverviewSetmeal } from '@/api/workspace'
import { getOrder, getOrderCount, takeOrder, rejectOrder, getOrderDetails, deliveryOrder } from '@/api/order'
import DialogOrderDetail from '@/components/DialogOrderDetail'
import OrderStatusNavVue from '@/components/OrderStatusNav.vue'
export default {
  name: 'DashboardIndex',
  components: {
    OrderStatusNavVue,
    DialogOrderDetail
  },
  data () {
    return {
      orderStatusNav: [
        {
          title: '待接单',
          status: 2,
          badge: 0
        },
        {
          title: '待派送',
          status: 3,
          badge: 0
        }
      ],
      pageTotal: 0,
      page: 1,
      pageSize: 10,
      orderList: [],
      status: 2,
      dialogVisibleReject: false,
      rejectReason: '',
      rejectReasonText: '',
      rejectReasonList: [
        { value: 1, label: '订单量较多，暂时无法接单' },
        { value: 2, label: '菜品已销售完，暂时无法接单' },
        { value: 3, label: '餐厅已打洋，暂时无法接单' },
        { value: 4, label: '自定义原因' }
      ],
      orderId: 0,
      dialogVisibleOrder: false,
      orderDetails: {},
      orderDishDetailList: [],
      todayBusinessData: {},
      ordersManageData: {},
      overviewDish: {},
      overviewSetmeal: {}
    }
  },
  created () {
    this.init()
  },
  methods: {
    handleStatus (status) {
      this.status = status
      this.getOrder()
    },
    async getOrder () {
      const res = await getOrder({
        beginTime: null,
        endTime: null,
        number: null,
        page: this.page,
        pageSize: this.pageSize,
        phone: null,
        status: this.status
      })
      if (res.code === 1) {
        this.orderList = res.data.records
        this.pageTotal = res.data.total
      }
    },
    async getOrderCount () {
      const res = await getOrderCount()
      if (res.code === 1) {
        this.orderStatusNav[0].badge = res.data.toBeConfirmed
        this.orderStatusNav[1].badge = res.data.confirmed
      }
    },
    async handleViewDetail (id) {
      await this.getOrderDetails(id)
      this.dialogVisibleOrder = true
    },
    async handleTakeOrder (id) {
      const res = await takeOrder(id)
      if (res.code === 1) {
        this.getOrder()
        this.$message.success('操作成功')
      } else {
        this.$message.error(res.msg)
      }
    },
    async rejectOrder () {
      const reason = this.rejectReasonList.find(item => item.value === this.rejectReason).label
      const res = await rejectOrder({
        id: this.orderId,
        rejectionReason: this.rejectReason === 4 ? this.rejectReasonText : reason
      })
      if (res.code === 1) {
        this.getOrder()
        this.$message.success('操作成功')
        this.dialogVisibleReject = false
      } else {
        this.$message.error(res.msg)
      }
    },
    handleRejectOrder (id) {
      this.dialogVisibleReject = true
      this.orderId = id
    },
    async getOrderDetails (id) {
      console.log(id)
      const res = await getOrderDetails(id)
      if (res.code === 1) {
        this.orderDetails = res.data
        this.orderDishDetailList = res.data.orderDishDetailList
      }
    },
    async handleBtnClick (state, id, autoNext) {
      if (state === 0) {
        await this.handleRejectOrder(id)
      } else if (state === 1) {
        await this.handleTakeOrder(id)
        if (autoNext) {
          const currentIndex = this.orderList.indexOf(this.orderList.find(item => item.id === id))
          const orderDetails = this.orderList[currentIndex + 1]
          this.orderDetails = orderDetails
          this.orderDishDetailList = orderDetails.orderDishDetailList
          this.dialogVisibleOrder = false
          setTimeout(() => {
            this.dialogVisibleOrder = true
          }, 500)
        }
      } else if (state === 2) {
        this.handleDelivery(id)
      }
      this.dialogVisibleOrder = false
    },
    async handleDelivery (id) {
      const res = await deliveryOrder(id)
      if (res.code === 1) {
        this.$message.success('操作成功')
        this.getOrder()
      } else {
        this.$message.error(res.msg)
      }
    },
    init () {
      this.getOrder()
      this.getOrderCount()
      this.getBusinessData()
      this.getOrdersData()
      this.getOverviewDish()
      this.getOverviewSetmeal()
    },
    // 查询今日运营数据
    async getBusinessData () {
      const res = await getBusinessData()
      if (res.code === 1) {
        this.todayBusinessData = res.data
      }
    },
    // 查询订单管理数据
    async getOrdersData () {
      const res = await getOrdersData()
      if (res.code === 1) {
        this.ordersManageData = res.data
      }
    },
    // 查询菜品总览
    async getOverviewDish () {
      const res = await getOverviewDish()
      if (res.code === 1) {
        this.overviewDish = res.data
      }
    },
    // 查询套餐总览
    async getOverviewSetmeal () {
      const res = await getOverviewSetmeal()
      if (res.code === 1) {
        this.overviewSetmeal = res.data
      }
    }
  }
}
</script>

<style lang="less" scoped>
.container {
  padding: 20px;
  background-color: #fff;
  border-radius: 5px;
}

.dashboard-index > div {
  margin-bottom: 20px;
}

.dashboard-index > div:last-child {
  margin-bottom: 0;
}

.today-data, .order, .dish-setmeal {
 .head {
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;

    > div{
      display: flex;
      align-items: baseline;
    }

    .left {
      gap: 8px;
      align-items: flex-end;

      .head-title {
        color: #333;
      }

      .head-time {
        font-size: 14px;
        color: #666;
      }
    }

    .right {
      gap: 5px;
      font-size: 14px;
      color: #666;
      cursor: pointer;

      .icon {
        font-size: 15px;
        font-weight: 600;
      }
    }
  }
}

.today-data, .order {
  .main .overview-list {
    display: flex;
    flex-wrap: wrap;
    gap: 20px;

    .overview-item {
      display: flex;
      flex-direction: column;
      gap: 10px;
      flex: 1;
      background-color: #FFFBF0;
      border-radius: 5px;
      padding: 20px;
      font-size: 14px;
      color: #333;
      min-width: 144px;

      .title-box {
        gap: 5px;
      }

      .overview-num {
        font-size: 28px;
        font-weight: 700;
      }
    }
  }
}

.order {
  .main .overview-list {
    .overview-item {
      flex-direction: row;
      align-items: center;
      justify-content: space-between;

      .icon {
        font-size: 28px;
        color: #333;
      }

      .title-box {
        display: flex;
        align-items: center;
      }
    }

    .overview-item:nth-of-type(1) .overview-num,
    .overview-item:nth-of-type(2) .overview-num {
      color: #fd3333;
    }
  }
}

.dish-setmeal {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;

  > div {
    flex: 1;
  }

  .main {
    display: flex;
    flex-wrap: wrap;
    gap: 20px;

    .overview-item {
      display: flex;
      flex-direction: row;
      align-items: center;
      justify-content: space-between;
      gap: 10px;
      flex: 2.5;
      background-color: #FFFBF0;
      border-radius: 5px;
      padding: 20px;
      font-size: 14px;
      color: #333;
      min-width: 149px;

      .title-box {
        display: flex;
        align-items: center;
        gap: 5px;

        .icon {
          font-size: 28px;
        }
      }

      .overview-num {
        font-size: 28px;
        color: #333;
        font-weight: 700;
      }
    }

    .add {
      background-color: #ffc100;
      color: #333;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      gap: 5px;
      font-size: 14px;
      border-radius: 5px;
      flex: 1;
      cursor: pointer;
      padding: 5px 0;
      min-width: 78px;

      .icon {
        font-size: 28px;
      }
    }
  }
}

.order-info {
  .head {
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;
  }

  .main {
    width: calc(100% - 5px);

    ::v-deep .el-table {
      font-size: 13px;
    }

    ::v-deep .el-table .ascending .sort-caret.ascending {
      border-bottom-color: #FFC100;
    }

    ::v-deep .el-table .descending .sort-caret.descending {
      border-top-color: #FFC100;
    }

    ::v-deep td.operate .cell {
      display: flex;
      justify-content: center;

      .btn {
        display: flex;
        border: 0;
        background-color: transparent;
        color: #419eff;
        margin-right: 20px;
        cursor: pointer;
      }

      .btn::after {
        display: block;
        content: "";
        width: 1px;
        height: 18px;
        background-color: #ebeef5;
        margin-left: 20px;
      }

      .btn:last-of-type::after {
        display: none;
      }

      .btn:last-of-type {
        margin-right: 0;
      }

      .btn:nth-of-type(2) {
        color: #f56c6c;
      }
    }
  }
}

::v-deep .el-dialog {
  .reject-box {
    padding: 20px 50px;

    > div {
      display: flex;
      align-items: center;
      max-width: 400px;
      margin-bottom: 20px;

      &:last-child {
        margin-bottom: 0;
      }

      span {
        flex: .5;
      }

      > div {
        flex: 2;
      }

      .el-textarea {
        width: auto;
      }
    }
  }
}

::v-deep .el-table {
  .el-table__header-wrapper {
    thead tr th:nth-child(7) {
      border-right: 1px solid #ebeef5;
    }
  }
}
</style>
